package wcg;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;


public class CSVReader  {
	
	private String Delimiter=  ",";
	
	private LinkedList<String[]> Lst = null;
	private FileReader FReader=null;
	private int IgnoreHeader = 0;
	
	/*
	 * 無視する行
	 */
	public void setIgnoreHeader(int iheader){
		IgnoreHeader = iheader;
	}
	/*
	 * 
	 */
	private void readCSV() throws IOException{
		if(Lst==null) Lst = new LinkedList<String[]>();
		else Lst.clear();
		BufferedReader br = new BufferedReader(FReader);
		String line;
		while ((line = br.readLine()) != null) {
			String[] tok = line.split(Delimiter);
			for (int jj = 0; jj < tok.length; jj++) {
				if (tok[jj].length() > 2) {
					if (tok[jj].charAt(0) == '"'
							&& tok[jj].charAt(tok[jj].length() - 1) == '"') {
						tok[jj] = tok[jj].substring(1, tok[jj].length() - 2);
					}
				}
				tok[jj] = tok[jj].trim();
			}
			Lst.add(tok);
		}
		br.close();
	}
	/*
	 * すべてのフィールドを返す。（ストリング配列のリスト）
	 */
	public LinkedList<String[]> getStringList() throws IOException{
		if(Lst==null) readCSV();
		LinkedList<String[]> ret = new LinkedList<String[]>();
		Iterator<String[]> ite = Lst.iterator();
		int idx = 0;
		while(ite.hasNext()){
			String[] s = ite.next();
			if(idx++>=IgnoreHeader){
				ret.add(s);
			}
		}
		return ret;
	}
	/*
	 * 行ごとのフィールド数を返す
	 */
	public int[] getFieldCount() throws IOException{
		if(Lst==null) readCSV();
		int sz = Lst.size();
		if(sz <= 0) return null;
		int [] ret = new int[sz];
		Iterator<String[]> ite = Lst.iterator();
		int idx = 0;
		while(ite.hasNext()){
			String[] a = ite.next();
			ret[idx++] = a.length;
		}
		
		return ret;
	}
	public CSVReader(FileReader fr){
		FReader = fr;
	}
}
